home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: I need some help re: scanf, getchar
- Date: 16 Feb 1996 22:20 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <16FEB199622201908@erich.triumf.ca>
- References: <4g3h6g$9ri@nkosi.well.com>
- NNTP-Posting-Host: erich.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4g3h6g$9ri@nkosi.well.com>, rickyarm@well.com () writes...
- >Hello there,
- >
- >My name is Rick Armanino and I am having some trouble with my program
- >for a class that I am taking. Can someone help with these problems??
- >
- >1. the first time through the do/while loop runs smooth; user enters
- >1 for entering new accounts finishes then the loop displays the menu
- >again but getchar() does not wait for the users input on the second
- >time around and goes straight to the default of the switch. WHY AND
- >WHERE IS GETCHAR GETING ITS INPUT FROM?
-
- scanf() is a poor function to use for direct user input. It is usually much
- better to use fgets(), then sscanf(), atoi(), or other things.
-
- As you have found, scanf() leaves a '\n' in the input buffer. If you just use
- scanf() this isn't a problem because the next scanf() will just eat the first
- '\n' it sees, then get the data you want. If you mix scanf() with getchar(),
- getchar() will see the left-over '\n' as a whole line and the getchar() will
- _appear_ to be missed.
-
- Another problem with scanf() occurs when it is expecting a number, and the user
- enters a letter - scanf() will look at the letter, see it doesn't meet the
- input spec, and put it back in the input buffer - you can loop all day trying
- to get correct input, and scanf() will keep looking at the same bad char, and
- rejecting it.
-
- If you use fgets(), you can easily check for valid input, and more easily
- recover from input errors (but remember that fgets() leaves an '\n' on the end
- of the input string - in some situations you will have to get rid of it before
- using the string.)
-
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
-
-